#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import re

reload(sys)
sys.setdefaultencoding("utf-8")

# 重庆a1表需要替换的字段，原由：a1表数据为累加数据，需做拆分处理
al_change_items = ["yysr", "yycb", "lrze", "tdywjsdynssde", "bzssr", "mssr", "gdzcjszjkctje", "mbyqndks", "SJLRE",
                   "YNSSDE", "JMSDSE", "sjyyjsdse", "tdywyjzsdse", "BQSJYBTSDSE", "JSYJNSRLJYYSR"]


def json_convert():
    # data = abc.get("data")
    # if data is not None:
    #     del abc["data"]

    res = {}
    # 取出原json其他数据并放到返回结果中
    # for k in abc:
    #     res[k] = abc[k]
    #
    # # 如果data为空返回空json
    # if data is None:
    #     res["data"] = {}
    #     return json.dumps(res, False)

    data = BODY
    newData = data.copy()

    # 纳税人登记信息
    syptSwdjxx = getJsonArray(data.get("nsrjbxx"))
    syptSwdjxxMap = {"fddbrxm": "FDDBRHFZRHYZXM", "fddbrsfzjlx": "FDDBRHFZRHYZSFZJZL_DM",
                     "fddbrsfzjhm": "FDDBRHFZRHYZSFZJHM", "fddbryddh": "FDDBRHFZRHYZYDDH"}

    syptSwdjxx = changeJsonKey(syptSwdjxx, syptSwdjxxMap)
    swdjxx = syptSwdjxx[0].get("nsrzglx")
    if "nsrzglx" in syptSwdjxx[0]:
        if swdjxx is None or swdjxx == "" or swdjxx == '':
            syptSwdjxx[0]["NSRZG_DM"] = '204'
        elif "一般纳税人" in swdjxx and "小规模纳税人" in swdjxx:
            syptSwdjxx[0]["NSRZG_DM"] = swdjxx
        elif "一般纳税人" in swdjxx:
            syptSwdjxx[0]["NSRZG_DM"] = '201'
        elif "小规模纳税人" in swdjxx:
            syptSwdjxx[0]["NSRZG_DM"] = '204'
        else:
            syptSwdjxx[0]["NSRZG_DM"] = swdjxx
    else:
        syptSwdjxx[0]["NSRZG_DM"] = None
    newData["syptSwdjxx"] = syptSwdjxx

    # 纳税信用等级
    syptSwpjxx = getJsonArray(data.get("nsxydj"))
    syptSwpjxxMap = {"pjnd": "SWXYPJSJ", "xydj": "SWXYPJ"}
    if syptSwpjxx != []:
        del newData["nsxydj"]
    newData["syptSwpjxx"] = changeJsonKey(syptSwpjxx, syptSwpjxxMap)

    # 增值税小规模申报信息
    syptZzsXgm = getJsonArray(data.get("zzsxgmsbxx"))
    if syptZzsXgm != []:
        del newData["zzsxgmsbxx"]
    for item in syptZzsXgm:
        try:
            skssqq = item.get("skssqq")
            skssqq = date_format(skssqq)
            skssqz = item.get("skssqz")
            skssqz = date_format(skssqz)
            if skssqz is not None:
                item["ND"] = str(skssqz.year)
                if skssqz.month < 10:
                    item["YF"] = "0" + str(skssqz.month)
                else:
                    item["YF"] = str(skssqz.month)
            else:
                continue

            # 应纳税额合计的本期数
            item = changeJsonSum(item, "YNSEHJDBNBQ", "ynsehjHl", "ynsehjFbw")

            # 应征增值税不含税销售额本期数
            item = changeJsonSum(item, "YZZZSHWJLWBHSXSEBNBQ", "yzzzsbhsxseHl", "yzzzsbhsxseFbw")

            # 销售、出租不动产不含税销售额
            item = changeJsonSum(item, "XSCZBDCBHSXSE", "xsczbdcbhsxseHl", "xsczbdcbhsxseFbw")

            # 免税货物及劳务销售额本期数
            item = changeJsonSum(item, "MSHWJLWXSEBNBQ", "msxseHl", "msxseFbw")

            # 出口免税货物销售额本期数
            item = changeJsonSum(item, "CKMSHWXSEBNBQ", "ckmsxseHl", "ckmsxseFbw")

            # 销售使用过的应税固定资产不含税销售额
            item = changeJsonSum(item, "XSSYGDYSGDZCBHSXSEBNBQ", "xssygdysgdzcbhsxseHl", "xssygdysgdzcbhsxseFbw")
        except:
            continue
    newData["syptZzsxgm"] = syptZzsXgm

    # 增值税一般纳税人申报
    syptZzsybnsr = getJsonArray(data.get("zzsybnsrsbxx"))
    if syptZzsybnsr != []:
        del newData["zzsybnsrsbxx"]
    for item in syptZzsybnsr:
        try:
            skssqq = item.get("skssqq")
            skssqq = date_format(skssqq)
            skssqz = item.get("skssqz")
            skssqz = date_format(skssqz)
            if skssqz is not None:
                item["ND"] = str(skssqz.year)
                if skssqz.month < 10:
                    item["YF"] = "0" + str(skssqz.month)
                else:
                    item["YF"] = str(skssqz.month)
            else:
                continue

            # 按适用税率计税销售额
            item = changeJsonSum(item, "ASYSLJSDNSJCYBJSE", "asysljsxseYb", "asysljsxseJzjt")

            # 按简易办法计税销售额
            item = changeJsonSum(item, "AJYZSBFZSHWXSE", "ajybfjsxseYb", "ajybfjsxseJzjt")

            # 免、抵、退办法出口销售额
            if "mdtbfckxseYb" in item:
                value = item.get("mdtbfckxseYb")
                item["MDTBFCKHWXSE"] = value
                del item["mdtbfckxseYb"]
            else:
                item["MDTBFCKHWXSE"] = None

            # 免税销售额
            if "msxseYb" in item:
                value = item.get("msxseYb")
                item["MSHWJLWXSE"] = value
                del item["msxseYb"]
            else:
                item["MSHWJLWXSE"] = None

            # 应纳税额合计
            item = changeJsonSum(item, "YNSEHJ", "ynsehjYb", "ynsehjJzjt")

            # 进项税额
            item = changeJsonSum(item, "JXSE", "jxseYb", "jxseJzjt")

            # 销项税额
            item = changeJsonSum(item, "XXSE", "xxseYb", "xxseJzjt")
        except:
            continue
    newData["syptZzsybnsr"] = syptZzsybnsr

    # 所得税A类月、季申报
    syptQysdsA1 = getJsonArray(data.get("qysdsalyjdsb"))
    if syptQysdsA1 != []:
        del newData["qysdsalyjdsb"]
    for item in syptQysdsA1:
        try:
            skssqq = item.get("skssqq")
            skssqq = date_format(skssqq)
            skssqz = item.get("skssqz")
            skssqz = date_format(skssqz)
            if skssqz is not None:
                item["ND"] = str(skssqz.year)
                if skssqz.month < 10:
                    item["YF"] = "0" + str(skssqz.month)
                else:
                    item["YF"] = str(skssqz.month)
            else:
                continue

            # 应纳所得税额
            if "ynsdse" in item:
                value = item.get("ynsdse")
                item["YNSSDE"] = value
                del item["ynsdse"]
            else:
                item["YNSSDE"] = None

            # 实际利润额/按照上一纳税年度应纳税所得额平均额确定的应纳税所得额
            if "sjlre" in item:
                value = item.get("sjlre")
                item["SJLRE"] = value
                del item["sjlre"]
            else:
                item["SJLRE"] = None

            # 减免所得税额
            if "jmsdse" in item:
                value = item.get("jmsdse")
                item["JMSDSE"] = value
                del item["jmsdse"]
            else:
                item["JMSDSE"] = None

            # 本期应补（退）所得税额/税务机关确定的本期应纳所得税额
            if "ybtsdse" in item:
                value = item.get("ybtsdse")
                item["BQSJYBTSDSE"] = value
                del item["ybtsdse"]
            else:
                item["BQSJYBTSDSE"] = None

            # 营业收入
            if "yysr" in item:
                value = item.get("yysr")
                item["JSYJNSRLJYYSR"] = value
                del item["yysr"]
            else:
                item["JSYJNSRLJYYSR"] = None
        except:
            continue
    syptQysdsA1 = sorted(syptQysdsA1, key=lambda a: a.get("skssqz")[:7], reverse=True)
    a1_items = []
    prev = None
    for i, item in enumerate(syptQysdsA1):
        for al_key in al_change_items:
            item[al_key + "_LJ"] = item.get(al_key)
        if check_item(item):
            if prev is not None:
                a1_items.append(minus_item(prev, item, 1))
            if i == len(syptQysdsA1) - 1:
                end_date = date_format(item.get("skssqz"))
                if end_date is not None:
                    a1_items.append(minus_item(item, dict(), end_date.month / 3))
                else:
                    a1_items.append(minus_item(item, dict(), 1))
            prev = item
        else:
            a1_items.append(item)
    newData["syptQysdsA1"] = a1_items

    # 所得税A类年报
    syptQysdsNd = getJsonArray(data.get("qysdsalnb"))
    if syptQysdsNd != []:
        del newData["qysdsalnb"]
    for item in syptQysdsNd:
        try:
            skssqq = item.get("skssqq")
            skssqq = date_format(skssqq)
            skssqz = item.get("skssqz")
            skssqz = date_format(skssqz)
            if skssqz is not None:
                item["ND"] = str(skssqz.year)
            else:
                continue

            # 应纳所得税额
            if "ynsdse" in item:
                value = item.get("ynsdse")
                item["YNSDSE"] = value
                del item["ynsdse"]
            else:
                item["YNSDSE"] = None
        except:
            continue
    newData["syptQysdsNd"] = syptQysdsNd

    # 欠税信息
    syptQsye = getJsonArray(data.get("qsxx"))
    syptQsyeMap = {"ybtse": "SE", "skssqq": "SSSQQ", "skssqz": "SSSQZ"}
    if syptQsye != []:
        del newData["qsxx"]
    newData["syptQsye"] = changeJsonKey(syptQsye, syptQsyeMap)

    # 违法信息
    wfwzztList = {u"登记待处理": "1",
                  u"责令限期改正": "2",
                  u"责令限期缴纳税款": "3",
                  u"调查巡查": "4",
                  u"税务行政处罚事项告知处理": "5",
                  u"税务行政处罚听证": "6",
                  u"简易程序处罚": "7",
                  u"一般程序处罚决定处理": "8",
                  u"延（分）期缴纳罚款申请审批": "9",
                  u"涉嫌犯罪案件移送": "10",
                  u"查补税款和罚款变更或补充处理": "11",
                  u"税务行政复议": "12",
                  u"复议终止处理": "13",
                  u"税务行政应诉": "14",
                  u"税务机关上诉处理": "15",
                  u"税务机关申诉与请求抗诉处理": "16",
                  u"稽查立案审批": "17",
                  u"稽查案件检查": "18",
                  u"稽查案件审理": "19",
                  u"重大税务案件审理": "20",
                  u"稽查案件执行": "21",
                  u"实施保全（简易）": "22",
                  u"实施保全": "23",
                  u"解除保全": "24",
                  u"停供（收缴）发票": "25",
                  u"解除停供（收缴）发票": "26",
                  u"提请吊销营业执照": "27",
                  u"强制执行登记": "28",
                  u"现金扣缴": "29",
                  u"强制扣缴": "30",
                  u"拍卖变卖": "31",
                  u"申请强制执行": "32",
                  u"行使代位（撤销）权": "33",
                  u"布控": "34",
                  u"撤控": "35",
                  u"涉税事项内部移送": "36",
                  u"征收开票": "37",
                  u"处理完毕": "38",
                  u"其他": "99"}
    wfwzlxList = {u"逃避缴纳税款": "01",
                  u"骗税": "02",
                  u"抗税": "03",
                  u"发票违法": "04",
                  u"违反税收管理": "05",
                  u"非主观故意违法": "06",
                  u"税务机关执法不当": "07",
                  u"税收政策例外": "08",
                  u"逃避追缴欠税": "09",
                  u"其他违法": "99"}
    syptWfwzxx = getJsonArray(data.get("wfwzxx"))
    syptWfwzxxMap = {"sswflx": "WFWZLX_DM", "sswfxwclzt": "WFXWCLZT_DM"}
    if syptWfwzxx != []:
        del newData["wfwzxx"]
    for wfwzItem in syptWfwzxx:
        ssqjq = wfwzItem.get("ssqjq")
        if ssqjq is not None:
            wfwzItem["DJRQ"] = ssqjq
            wfwzItem["LARQ"] = ssqjq
        else:
            wfwzItem["DJRQ"] = None
            wfwzItem["LARQ"] = None
        if "sswflx" in wfwzItem:
            sswflx = wfwzItem.get("sswflx")
            value = wfwzlxList.get(sswflx)
            if value is not None:
                wfwzItem["WFWZLX_DM"] = value
            else:
                wfwzItem["WFWZLX_DM"] = sswflx
            del wfwzItem["sswflx"]
        else:
            wfwzItem["WFWZLX_DM"] = None
        if "sswfxwclzt" in wfwzItem:
            sswfxwclzt = wfwzItem.get("sswfxwclzt")
            value = wfwzztList.get(sswfxwclzt)
            if value is not None:
                wfwzItem["WFXWCLZT_DM"] = value
            else:
                wfwzItem["WFXWCLZT_DM"] = sswfxwclzt
            del wfwzItem["sswfxwclzt"]
        else:
            wfwzItem["WFXWCLZT_DM"] = None
    newData["syptWfwzxx"] = changeJsonKey(syptWfwzxx, syptWfwzxxMap)

    res["data"] = newData
    return json.dumps(res, False)


def isfloat(x):
    try:
        if isinstance(float(x), float):
            if str(x) in ["inf", "infinity", "INF", "INFINITY", "True"]:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def changeJsonKey(jsonArr, jsonMap):
    """
    替换掉json数组中的所有需要替换的字段
    :param jsonArr: 需要替换的json
    :param jsonMap: 替换的映射json，key为原字段，value为替换后的字段
    :return:
    """
    for obj in jsonArr:
        items = jsonMap.items()
        for k, v in items:
            try:
                value = obj.get(k)
                if value is not None:
                    obj[v] = value
                    del obj[k]
                else:
                    obj[v] = obj.get(v)
            except:
                continue

    return jsonArr


def changeJsonSum(jsonObj, newKey, *oldKeys):
    """
    把oldKeys的字段值加起来，然后放到newKey里面，然后返回,如果需要相加的字段存在数字，则返回结果和，否则返回拼接字符串
    :param jsonObj: 需要处理的json数据
    :param newKey: 新生成的key
    :param oldKeys: 处理的原key，可能存在多个
    :return:
    """
    try:
        flag = False
        sumNum = 0
        sumStr = ""
        for i in oldKeys:
            v = jsonObj.get(i)
            if isfloat(v):
                flag = True
                sumNum = sumNum + float(v)
                sumStr = sumStr + str(v)
            else:
                if v is not None:
                    sumStr = sumStr + v
        if flag:
            jsonObj[newKey] = sumNum
        else:
            jsonObj[newKey] = sumStr
        return jsonObj
    except:
        return jsonObj


def date_format(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None


def check_item(item):
    start_date = date_format(item.get("skssqq"))
    end_date = date_format(item.get("skssqz"))
    if start_date is not None and end_date is not None and end_date.month in [3, 6, 9, 12] \
            and end_date.month - start_date.month == 2:
        return True
    else:
        return False


def minus(val1, val2, season):
    if isfloat(val1) and isfloat(val2):
        return round((float(val1) - float(val2)) / season, 4)
    elif isfloat(val1):
        return round(float(val1) / season, 4)
    else:
        return val1


def minus_item(curr_item, next_item, season):
    curr_date = date_format(curr_item.get("skssqz"))
    next_date = date_format(next_item.get("skssqz"))
    if next_date is not None and curr_date.year != next_date.year:
        return curr_item
    for al_key in al_change_items:
        curr_item[al_key] = minus(curr_item.get(al_key), next_item.get(al_key), season)
    return curr_item


def getJsonObject(jsonObj):
    try:
        return jsonObj if isinstance(jsonObj, dict) else {}
    except:
        return {}


def getJsonArray(jsonArr):
    try:
        return jsonArr if isinstance(jsonArr, list) else []
    except:
        return []


def getStr(str):
    if str is None:
        return ""
    else:
        return str


if __name__ == "__main__":
    file_obj = open(r"../data/TX_CQ_DSJ_PRE.json", "r")
    content = file_obj.read()
    abc = json.loads(content, strict=False)
    aa = json_convert()
    print aa

result = json_convert()
